import routes from '@/router/router'
import utils from '@/lib/utils';
import {AppMenuState,MenuItem,MenuTag} from "@/types/menu";
import Cookie from '@/lib/cookie/index'
export interface AppState {
  menuState: AppMenuState,
  tagList: Array<MenuTag>,
  breadCrumbs: Array<MenuItem>,
  collapse: boolean,
  language: string
}
const state = (): AppState => ({
  menuState: {
    defaultActive: sessionStorage.getItem('defaultActive') || 'Home',
    defaultOpens: JSON.parse(sessionStorage.getItem('defaultOpens') || '[]'),
  },
  tagList: JSON.parse(sessionStorage.getItem('tagList') || "[{\"path\":\"/home\",\"name\":\"Home\",\"title\":\"欢迎首页\",\"lang\":\"home\"}]"),
  breadCrumbs: JSON.parse(sessionStorage.getItem('breadCrumbs') || '[]'),
  collapse: false,
  language: Cookie.getItem('language') || 'zh-cn'
})

const getters = {
  menuList(): Array<MenuItem> {
    return utils.getMenuList(routes)
  }
}

const mutations = {
  setMenuState(state: AppState, data: AppMenuState): void{
    state.menuState.defaultActive = data.defaultActive
    state.menuState.defaultOpens = data.defaultOpens
    sessionStorage.setItem('defaultActive',data.defaultActive)
    sessionStorage.setItem('defaultOpens',JSON.stringify(data.defaultOpens))
  },
  setTagList(state: AppState, list: Array<MenuTag>){
    state.tagList = list
  },
  pushTag(state: AppState, item: MenuTag){
    state.tagList.push(item)
    sessionStorage.setItem('tagList', JSON.stringify(state.tagList))
  },
  removeTag(state: AppState, tag: MenuTag){
    state.tagList = state.tagList.filter((item) => item.path !== tag.path)
    sessionStorage.setItem('tagList', JSON.stringify(state.tagList))
  },
  removeTagsAll(state: AppState){
    state.tagList = state.tagList.filter((item:MenuTag) => item.name === 'Home')
    sessionStorage.setItem('tagList', JSON.stringify(state.tagList))
  },
  removeTagsOther(state: AppState){
    state.tagList = state.tagList.filter((item:MenuTag) => item.path === '/home' || item.path === state.menuState.defaultActive)
    sessionStorage.setItem('tagList', JSON.stringify(state.tagList))
  },
  setBreadCrumbs(state: AppState, data: Array<MenuItem>){
    state.breadCrumbs = data
    sessionStorage.setItem('breadCrumbs', JSON.stringify(state.breadCrumbs))
  },
  setCollapse(state: AppState){
    state.collapse = !state.collapse
  },
  setLanguage(state: AppState, language: string){
    state.language = language
    Cookie.setItem('language', language)
  },
}

export default {
  state,
  getters,
  mutations,
}
